//
//  HomeTableViewController.swift
//  新浪微博
//
//  Created by 焦林生 on 15/11/3.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit
import SVProgressHUD

//原创微博 可重用cell表示符号
 let statusCellNormalId = "statusCellNormalId"
//转发微博cell的可重用标示符号
let StatusCellRetweetedId = "StatusCellRetweetedId"

class HomeTableViewController: VisitorTableViewController {

    //微博列表视图模型
    private lazy var listViewModel = StatusListViewModel()
    
    //照片浏览转场动画代理
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !UserAccountViewModel.sharedUserAccount.userLogin {
        
             visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        
        loadData()
        
        //MARK: 注册通知(注意循环引用)
        NSNotificationCenter.defaultCenter().addObserverForName(LJStatusSelectPhotoNotification,
            object: nil,
            queue: nil) { [weak self] (n) -> Void in
            
                guard let urls = n.userInfo?[LJStatusSelectPhotoURLKey] as? [NSURL] else {
                
                    return
                }
                
                guard let indexPath  = n.userInfo?[LJStatusSelectPhotoIndexPathKey] as? NSIndexPath else {
                
                    return
                }
                guard let cell = n.object as? PhotoBrowserPresentDelegate else {
                
                    return
                }
                
                let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
                
                //1 设置转场动画类型
                vc.modalPresentationStyle = UIModalPresentationStyle.Custom
                
                //2 设置转场动画代理
                vc.transitioningDelegate = self?.photoBrowserAnimator
                
                //3 设置转场动画参数
                self?.photoBrowserAnimator.setDelegateParams(cell, dismissDelegate: vc, indexPath: indexPath)
                
                //4 modal 展现
                self?.presentViewController(vc, animated: true, completion: nil)
        }
        
       
    }
    //注销通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
   //准备表格
    private func prepareTableView() {
    
        //注册可重用cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: statusCellNormalId)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusCellRetweetedId)
        
        //取消分割线
        tableView.separatorStyle = .None
        
        //设置一个预估行高
        tableView.estimatedRowHeight = 400
        
        //下拉刷新控件默认没有 - 高度 60
        refreshControl = LJRefreshControl()
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        //上拉刷新视图
        tableView.tableFooterView = pullupView
        

    }
    
    //加载数据
    @objc private func loadData() {
        
        self.refreshControl?.beginRefreshing()
        //以上拉视图的动画状态 作为参数的传递
        listViewModel.loadStatus(isPullup: pullupView.isAnimating()) { (isSuccessed) -> () in
               //关闭刷新控件
              self.refreshControl?.endRefreshing()
              //关闭上拉刷新
              self.pullupView.stopAnimating()
            
            if !isSuccessed {
            
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                  return
            }
            //显示下拉刷新提示
            self.showpulldownTip()

            //刷新数据
            self.tableView.reloadData()
         
        }
        
     
    }
    
    //显示下拉刷新
    private func showpulldownTip() {
    
        //如果不是下拉刷新 直接返回
        guard let count = listViewModel.pulldownCount else {
        
            return
        }
        
        pulldownTipLabel.text = (count == 0) ? "没有新微博" : "刷新到\(count)条微博"
        
        let height: CGFloat = 44
        let rect = CGRect(x: 0, y: 0, width: view.bounds.width, height: height)

        pulldownTipLabel.frame = CGRectOffset(rect, 0, -2 * height)
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.0){
                    
                    self.pulldownTipLabel.frame = CGRectOffset(rect, 0, -2 * height)
                }
        }
        
    }
    
    //MARK: - 懒加载控件
    //下拉刷新提示标签
    private lazy var pulldownTipLabel: UILabel = {
    
        let label = UILabel(title: "", fontSize: 18, color: UIColor.whiteColor())
        label.backgroundColor = UIColor.orangeColor()
        
        //添加到 navigationBar
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)

        
        return label
    }()
    
    //MARK: 懒加载控件
    //上拉刷新提示视图
    private lazy var pullupView: UIActivityIndicatorView = {
    
        let indicator = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        
        return indicator
    }()
   
}

// MARK: - 数据源方法
extension HomeTableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //1 获取微博视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        //2 获取可重用cell 获取行高
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellID, forIndexPath: indexPath) as! StatusCell
        
        //3 设置视图模型
        cell.viewModel = vm
        
        //4 判断是否是最一条微博
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
        
            //开始动画
            pullupView.startAnimating()
            
            //上拉刷新
            loadData()
            
            print("上拉刷新数据")
        }
        
        return cell
    }
    //行高代理方法
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return listViewModel.statusList[indexPath.row].rowHeight
    }
}




